import { useStore } from 'vuex';
import { computed } from 'vue';

// 购物车相关逻辑
export const useCommonCartEffect = (shopId) => {
  const store = useStore();
  const cartList = store.state.cartList;
  const changeCartItemInfo = (shopId, productId, productInfo, num) => {
    store.commit('changeCartItemInfo', { shopId, productId, productInfo, num });
  };

  // 当前商铺下购物车信息
  const productList = computed(() => {
    const productList = cartList[shopId]?.productList || {};
    const notEmptyProductList = {};
    for (let item in productList) {
      const product = productList[item];
      if (product.count > 0) {
        notEmptyProductList[item] = product;
      }
    }
    console.log('notEmptyProductList: ', notEmptyProductList);
    return notEmptyProductList;
  });
  const shopName = computed(() => {
    const shopName = cartList[shopId]?.shopName || '';
    return shopName;
  });

  const calculations = computed(() => {
    const productList = cartList[shopId]?.productList; //获取当前商铺商品列表
    // 商品总数 // 商品总价 // 是否全选
    const result = { total: 0, price: 0, allChecked: true };
    if (productList) {
      for (let item in productList) {
        const product = productList[item];
        result.total += product.count;
        if (product.check) {
          //选中商品才计入总价
          result.price += product.count * product.price;
        }
        if (product.count > 0 && !product.check) {
          result.allChecked = false;
        }
      }
    }
    result.price = result.price.toFixed(2);
    return result;
  });
  return { cartList, shopName, productList, calculations, changeCartItemInfo };
};
